﻿using System;
using Helper;

namespace FileRenamer
{
	public class CommandBuilder
	{
		public string Output;
		public CommandBuilder(CodeBlock codeBlock)
		{
			Output = Eval(codeBlock);
		}
		private string Eval(CodeBlock codeBlock)
		{
			if (codeBlock.Children.Count == 0)
			{
				string input, commandName, command = "";
				if (codeBlock.Block.IndexOf(':') == -1) return codeBlock.Block;
				input = codeBlock.Block.Substring(0, codeBlock.Block.LastIndexOf(':'));
				commandName = codeBlock.Block;//codeBlock.Block.Substring(input.Length + 1, codeBlock.Block.IndexOf('(') - input.Length - 1);
				if (input.Length > 0) commandName = codeBlock.Block.Replace(input, "");
				commandName = commandName.Substring(1);
				if (commandName.IndexOf('(') >= 0)
				{
					commandName = commandName.Substring(0, commandName.IndexOf('('));
					command = codeBlock.Block.Substring(input.Length + commandName.Length + 2);
					command = command.Replace(")", "");
				}
				//ICommand comm = Globals.Commands.Find(e => e.CommandName == commandName);
				//if (comm == null || Globals.Settings.DisabledExtensions.Contains(comm.GetType())) return input;
				return Globals.Commands.Find(e => e.CommandName == commandName).Convert(input, command.Split(','));
			}
			else
			{
				string output = codeBlock.Block;
				foreach (CodeBlock block in codeBlock.Children)
				{
					string replaceText = block.Block;
					if (!replaceText.StartsWith("{") && !replaceText.EndsWith("}")) replaceText = "{" + replaceText + "}";
					output = output.Replace(replaceText, Eval(block));
				}
				//create a new inner codeblock with it's contents completely evaluated. Then eval that codeblock.
				return Eval(new CodeBlock(output, false));
			}
		}
	}
}
